<template>
  <div class="match-statistics-container">
    <div class="page-header">
      <h2 class="page-title">匹配统计</h2>
      <div class="header-actions">
        <el-date-picker
            v-model="filterForm.year"
            :clearable="false"
            format="YYYY"
            placeholder="选择年份"
            type="year"
            value-format="YYYY"
            @change="handleFilter"
        />
        <el-button type="primary" @click="refreshData">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
<!--    <el-card class="filter-card">-->
<!--      <el-form :model="filterForm" inline>-->
<!--        <el-form-item label="供应商">-->
<!--          <el-select v-model="filterForm.supplierName" :style="{ width: '220px' }" clearable filterable-->
<!--                     placeholder="请选择供应商">-->
<!--            <el-option label="全部" value=""></el-option>-->
<!--            <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label"-->
<!--                       :value="item.value"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="单据类型">-->
<!--          <el-select v-model="filterForm.documentType" :style="{ width: '150px' }" clearable-->
<!--                     placeholder="请选择单据类型">-->
<!--            <el-option label="全部" value=""></el-option>-->
<!--            <el-option label="订单" value="订单"></el-option>-->
<!--            <el-option label="收货单" value="收货单"></el-option>-->
<!--            <el-option label="发票" value="发票"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" @click="handleFilter">查询</el-button>-->
<!--          <el-button @click="resetFilter">重置</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </el-card>-->

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col v-for="(item, index) in overviewCards" :key="index" :span="6">
        <el-card :body-style="{ padding: '15px' }" class="statistics-card">
          <div class="statistics-card-content">
            <div :class="'text-' + item.color" class="card-value">{{
                (statistics?.overview && statistics.overview[item.field] !== undefined) ? statistics.overview[item.field] : '0'
              }}
            </div>
            <div class="card-title">{{ item.title }}</div>
            <el-icon :class="'icon-' + item.color" class="card-icon">
              <component :is="item.icon"></component>
            </el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card :body-style="{padding: '20px'}" class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>匹配状态分布</h3>
            </div>
          </template>
          <div ref="statusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card :body-style="{padding: '20px'}" class="chart-card">
          <template #header>
            <div class="chart-header">
              <h3>月度匹配趋势</h3>
            </div>
          </template>
          <div id="trendChart" ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, onUnmounted, reactive, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {getMatchStatistics} from '@/api/match';
import * as echarts from 'echarts';
import {Refresh} from '@element-plus/icons-vue';

// 图表实例
let statusChart: echarts.ECharts | null = null;
let trendChart: echarts.ECharts | null = null;

// 状态控制
const loading = ref(false);
const statistics = ref<any>({});

// 供应商选项
const supplierOptions = reactive([
  {value: '江南机械厂', label: '江南机械厂'},
  {value: '东方自动化设备', label: '东方自动化设备'},
  {value: '华宇工业集团', label: '华宇工业集团'},
  {value: '北辰科技', label: '北辰科技'},
  {value: '南洋电子', label: '南洋电子'}
]);

// 筛选表单
const filterForm = reactive({
  year: new Date().getFullYear().toString(), // 默认当前年份
  supplierName: '',
  documentType: ''
});

// DOM元素引用
const statusChartRef = ref<HTMLDivElement | null>(null);
const trendChartRef = ref<HTMLDivElement | null>(null);

// 初始化统计数据，防止出现undefined引用错误
const defaultStats = {
  overview: {
    totalMatches: 0,
    successMatches: 0,
    partialMatches: 0,
    pendingMatches: 0,
    exceptionMatches: 0,
    successRate: '0%',
    averageMatchTime: '0小时'
  },
  statusDistribution: [],
  monthlyTrend: []
};

// 数据概览卡片配置
const overviewCards = [
  {title: '匹配总数', field: 'totalMatches', icon: 'DataLine', color: 'primary'},
  {title: '成功匹配', field: 'successMatches', icon: 'SuccessFilled', color: 'success'},
  {title: '异常匹配', field: 'exceptionMatches', icon: 'WarningFilled', color: 'danger'},
  {title: '成功率', field: 'successRate', icon: 'DataAnalysis', color: 'success'}
];

// 初始化
onMounted(() => {
  try {
    // 初始值赋值，避免空引用
    statistics.value = defaultStats;
    // 初始化图表
    initCharts();
    // 加载数据
    fetchData();
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  } catch (error) {
    console.error('组件挂载时发生错误:', error);
  }
});

// 组件卸载前清理资源
onUnmounted(() => {
  try {
    // 移除事件监听
    window.removeEventListener('resize', handleResize);

    // 销毁图表实例
    if (statusChart) {
      statusChart.dispose();
      statusChart = null;
    }

    if (trendChart) {
      trendChart.dispose();
      trendChart = null;
    }
  } catch (error) {
    console.error('组件卸载时发生错误:', error);
  }
});

// 监听statistics的变化，在数据变化时更新图表
watch(() => statistics.value, (newValue, oldValue) => {
  // 确保页面DOM已经渲染完成
  setTimeout(() => {
    // 先初始化图表
    initCharts();
    // 再更新图表数据
    updateCharts();
  }, 100);
}, {deep: true});

// 加载数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params: any = {};

    if (filterForm.year) {
      // 直接传递年份，让后端处理
      params.startDate = filterForm.year;
    }

    if (filterForm.supplierName) {
      params.supplierName = filterForm.supplierName;
    }

    if (filterForm.documentType) {
      params.documentType = filterForm.documentType;
    }

    const response = await getMatchStatistics(params);

    if (response.code === 200) {
      if (response.data) {
        statistics.value = response.data;
      } else {
        console.warn('服务器返回了空数据，使用默认值');
        statistics.value = defaultStats;
        ElMessage.warning('暂无匹配统计数据');
      }
      // 更新图表
      updateCharts();
    } else {
      console.error('获取统计数据失败:', response.message);
      ElMessage.error('获取统计数据失败：' + (response.message || '未知错误'));
      // 使用默认数据
      statistics.value = defaultStats;
      updateCharts();
    }
  } catch (error) {
    console.error('获取统计数据异常:', error);
    ElMessage.error('获取统计数据异常，请稍后重试');
    // 使用默认数据
    statistics.value = defaultStats;
    updateCharts();
  } finally {
    loading.value = false;
  }
};

// 初始化图表
const initCharts = () => {
  try {
    // 清理现有图表实例
    if (statusChart) {
      statusChart.dispose();
      statusChart = null;
    }
    if (trendChart) {
      trendChart.dispose();
      trendChart = null;
    }

    // 状态分布图表
    if (statusChartRef.value) {
      statusChart = echarts.init(statusChartRef.value);
    }

    // 趋势图表
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value);
    }

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', handleResize);
  } catch (error) {
    console.error('初始化图表时出错:', error);
  }
};

// 更新图表
const updateCharts = () => {
  try {
    if (!statistics.value) return;

    // 更新状态分布图表
    if (statusChart && statistics.value.statusDistribution) {
      try {
        // 创建一个新数组而不是修改原始数据
        const statusData = statistics.value.statusDistribution.map((item: any) => {
          return {
            name: item.matchResult || item.status || '未知状态',
            value: item.count || 0
          };
        });

        // 设置饼图颜色
        const colorMap = {
          '匹配': '#67C23A',   // 成功 - 绿色
          '部分匹配': '#E6A23C', // 警告 - 橙色
          '待匹配': '#909399',   // 信息 - 灰色
          '不匹配': '#F56C6C'  // 错误 - 红色
        };

        statusChart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 10,
            data: statusData.map((item: any) => item.name),
            formatter: (name) => {
              const item = statusData.find((data) => data.name === name);
              return `${name}: ${item ? item.value : 0}`;
            }
          },
          series: [
            {
              name: '匹配状态',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: true,
                position: 'outside',
                formatter: '{b}: {c} ({d}%)'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: true
              },
              data: statusData.map((item) => ({
                ...item,
                itemStyle: {
                  color: colorMap[item.name] || '#409EFF'
                }
              }))
            }
          ]
        });
      } catch (error) {
        console.error('更新状态分布图表时出错:', error);
      }
    } else {
      console.warn('状态分布图表实例不存在或数据为空');
    }

    // 更新趋势图表
    if (trendChart && statistics.value.monthlyTrend) {
      try {
        const monthlyTrend = statistics.value.monthlyTrend || [];

        // 确保数据按月份排序
        monthlyTrend.sort((a, b) => {
          if (!a.date || !b.date) return 0;
          return a.date.localeCompare(b.date);
        });

        // 提取月份标签 - 使用"MM月"格式
        const months = monthlyTrend.map(item => {
          if (!item.date) return '';
          // 从日期中提取月份 (格式: YYYY-MM)
          const monthParts = item.date.split('-');
          if (monthParts.length >= 2) {
            return `${monthParts[1]}月`;
          }
          return '';
        });

        // 提取数据
        const totalData = monthlyTrend.map(item => item.total || 0);
        const successData = monthlyTrend.map(item => item.success || 0);
        const partialData = monthlyTrend.map(item => item.partial || 0);
        const pendingData = monthlyTrend.map(item => item.pending || 0);
        const exceptionData = monthlyTrend.map(item => item.exception || 0);

        trendChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function (params) {
              let result = params[0].name + '<br/>';
              params.forEach(param => {
                result += `${param.seriesName}: ${param.value}个<br/>`;
              });
              return result;
            }
          },
          legend: {
            data: ['匹配总数', '成功匹配', '不匹配'],
            selectedMode: 'multiple'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: months,
            axisLabel: {
              interval: 0,
              rotate: window.innerWidth < 768 ? 30 : 0 // 在小屏幕上旋转标签
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '数量',
              nameTextStyle: {
                color: '#666'
              },
              axisLabel: {
                formatter: '{value}个'
              }
            }
          ],
          series: [
            {
              name: '匹配总数',
              type: 'bar',
              barWidth: '40%',
              itemStyle: {
                color: '#409EFF'
              },
              data: totalData
            },
            {
              name: '成功匹配',
              type: 'line',
              smooth: true,
              symbolSize: 6,
              lineStyle: {
                width: 3
              },
              itemStyle: {
                color: '#67C23A'
              },
              data: successData
            },
            {
              name: '不匹配',
              type: 'line',
              smooth: true,
              symbolSize: 6,
              lineStyle: {
                width: 3
              },
              itemStyle: {
                color: '#F56C6C'
              },
              data: exceptionData
            }
          ]
        });
      } catch (error) {
        console.error('更新月度趋势图表时出错:', error);
      }
    } else {
      console.warn('月度趋势图表实例不存在或数据为空');
    }
  } catch (error) {
    console.error('更新图表时出错:', error);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (statusChart) statusChart.resize();
  if (trendChart) trendChart.resize();
};

// 刷新数据
const refreshData = () => {
  fetchData();
};

// 查询
const handleFilter = () => {
  fetchData();
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.year = new Date().getFullYear().toString();
  filterForm.supplierName = '';
  filterForm.documentType = '';
  fetchData();
};
</script>

<style scoped>
.match-statistics-container {
  padding: 20px 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-card {
  margin-bottom: 25px;
  border-radius: 8px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.08);
}

.statistics-row {
  margin-bottom: 25px;
}

.statistics-card {
  height: 150px;
  overflow: hidden;
  transition: all 0.3s;
  border-radius: 8px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.08);
  margin-bottom: 25px;
}

.statistics-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.statistics-card-content {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 5px 15px;
}

.card-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 10px;
}

.card-title {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.card-icon {
  position: absolute;
  right: 15px;
  bottom: 15px;
  font-size: 56px;
  opacity: 0.15;
}

.chart-row {
  margin-bottom: 25px;
}

.chart-card {
  margin-bottom: 25px;
  border-radius: 8px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.chart-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.chart-header,
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3,
.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.progress-bar-container {
  position: relative;
  width: 100%;
  height: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: #409eff;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  font-size: 12px;
}

/* 颜色定义 */
.text-primary {
  color: #409eff;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}

.text-info {
  color: #909399;
}

.icon-primary {
  color: #409eff;
}

.icon-success {
  color: #67c23a;
}

.icon-warning {
  color: #e6a23c;
}

.icon-danger {
  color: #f56c6c;
}

.icon-info {
  color: #909399;
}
</style> 